package com.mezizy.ifaner;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

import com.mezizy.ifaner.global.Config;
import com.mezizy.ifaner.global.Global;
 import com.mezizy.ifaner.global.com.mezizy.ifaner.web.data.User;
import com.zftlive.android.common.VersionChecker;


public class LogInActivity extends ActionBarActivity {
    EditText editStuId;
    EditText editStuPwd;

    //private String stuId;
    //private String stuPwdSha;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log_in);
        getSupportActionBar().hide();

        VersionChecker.requestCheck(this, Config.VERSION_CHECKER);

        editStuId = (EditText) findViewById(R.id.editLogInStuId);
        editStuPwd = (EditText) findViewById(R.id.editLogInStuPwd);

        SharedPreferences settings = getSharedPreferences(Config.SHARED_PREFERENCE, 0); // 获取一个SharedPreferences对象

        String userId = settings.getString(Config.SHARED_ID, ""); // 取出保存的NAME
        String userPwd = settings.getString(Config.SHARED_PWD_SHA, ""); // 取出保存的PASSWORD

        if ((!userId.isEmpty())&&(!userPwd.isEmpty())){
            if (getIntent() != null && getIntent().getExtras() != null && getIntent().getBooleanExtra("isLogOut",false) == true) {
            } else {
                checkUser(userId,userPwd);
            }
        }

        // Set value
        editStuId.setText(userId); // 将取出来的用户名赋予field_name
        editStuPwd.setText(userPwd); // 将取出来的密码赋予filed_pass



        (findViewById(R.id.btnLogIn)).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        v.setBackgroundResource(R.drawable.log_in_button_dark);

                        break;

                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_UP:

                        v.setBackgroundResource(R.drawable.log_in_button);
                        break;
                }
                return false;
            }
        });

    }

    public void btnSignUpClicked(View view) {
        startActivity(new Intent(LogInActivity.this, SignUpActivity.class));
    }

    @Override
    protected void onStart() {
        super.onStart();
        Global.appContext = getApplicationContext();


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_log_in, menu);
        return true;
    }

    public void logInBtnClicked(View view) {
        Global.showProgress(this, "登錄中，請稍後");
        String stuId = editStuId.getText().toString();
        String stuPwd =  editStuPwd.getText().toString();

        checkUser(stuId,stuPwd);
        /*
        test
         */
/*        if (stuId.equals("")) {
            Global.showToast("got here!");
            Global.userId = "02132421";
            Global.userPwdSha = Global.encrypt("123456");
            Global.userCredit = 80;
            Global.userName = "Zizy";
            Global.dismissProgress(LogInActivity.this);

            startActivity(new Intent(LogInActivity.this, MainActivity.class));

            return;
        }*/




    }
    private void checkUser(final String stuId, final String stuPwd) {
        final String stuPwdSha = Global.encrypt(stuPwd);
        new Thread(new Runnable() {
            @Override
            public void run() {
                int result = Global.userAuthorize(stuId, stuPwdSha);
                if (result == Config.IFANER_LOG_IN_SUCCESS) {
                    Global.showToast("Welcome!", LogInActivity.this);

                    Global.userId = stuId;
                    Global.userPwdSha = stuPwdSha;
                    User user = Global.getUserInf();
                    Global.userCredit = user.getUserCredit();
                    Global.userName = user.getUserName();


                    // 首先获取一个SharedPreferences对象
                    SharedPreferences settings = getSharedPreferences(Config.SHARED_PREFERENCE, 0);
                    // 将用户名和密码保存进去
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString(Config.SHARED_ID, stuId);
                    editor.putString(Config.SHARED_PWD_SHA, stuPwd);
                    editor.commit();


                    Global.dismissProgress(LogInActivity.this);
                    startActivity(new Intent(LogInActivity.this, MainActivity.class));

                } else if (result == Config.IFANER_LOG_IN_FAILED_AU) {
                    Global.showToast("Log in failed! Please check your id and password. ", LogInActivity.this);
                } else if (result == Config.IFANER_LOG_IN_FAILED_INTERNET) {
                    Global.showToast("Log in failed! Please check the internet connection. ", LogInActivity.this);
                }
                Global.dismissProgress(LogInActivity.this);

            }
        }).start();
    }
    @Override
    protected void onStop() {
        super.onStop();
        Global.dismissProgress(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        Intent startMain = new Intent(Intent.ACTION_MAIN);
        startMain.addCategory(Intent.CATEGORY_HOME);
        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(startMain);
        System.exit(0);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
